package dbx

import (
	"crypto/tls"
	"crypto/x509"
	"net/url"
	"os"
)

const (
	disable = "disable"
)

type TLS struct {
	Enable bool   `json:"enable" toml:"enable"`
	Mode   string `json:"mode" toml:"mode"`
	Cert   string `json:"cert" toml:"cert"`
	Key    string `json:"key" toml:"key"`

	CaCert string `json:"ca_cert" toml:"ca_cert"`
}

func (r TLS) Tls() *tls.Config {
	caCert, err := os.ReadFile(r.CaCert)
	if err != nil {
		panic(err)
	}
	caCertPool := x509.NewCertPool()
	if ok := caCertPool.AppendCertsFromPEM(caCert); !ok {
		panic("Error: CA file must be in PEM format")
	}
	tlsConfig := tls.Config{
		RootCAs: caCertPool,
	}
	return &tlsConfig
}
func (r TLS) MTls(t *tls.Config) *tls.Config {
	cert, err := tls.LoadX509KeyPair(r.Cert, r.Key)
	if err != nil {
		panic(err)
	}
	t.Certificates = []tls.Certificate{cert}
	return t
}

func (r TLS) IsEnable() bool {
	return r.Enable
}

type DataBase struct {
	UserName string `mapstructure:"username" toml:"username" yaml:"username" json:"username"`
	Password string `mapstructure:"password" toml:"password" yaml:"password" json:"password"`
	Address  string `mapstructure:"address" toml:"address" yaml:"address" json:"address"`
	DbName   string `mapstructure:"db_name" toml:"db_name" yaml:"db_name" json:"db_name"`
}
type IDataBase interface {
	DSN(query url.Values) string
}
type ReplicaSet struct {
	RsName   string   `mapstructure:"rs_name" toml:"rs_name" yaml:"rs_name" json:"rs_name"`
	UserName string   `mapstructure:"username" toml:"username" yaml:"username" json:"username"`
	Password string   `mapstructure:"password" toml:"password" yaml:"password" json:"password"`
	Addrs    []string `mapstructure:"addrs" toml:"addrs" yaml:"addrs" json:"addrs"`
}
